import os
import sys
import datetime
import time
import hashlib
import requests
from fake_useragent.fake import UserAgent
from tuiqiuspiderPro.settings import IMGURLHEAD

BASE_DIR = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
IMAGE_DIR = os.path.join(BASE_DIR, 'img')


def SaveImg(url, source=None):
    """
    下载图片并保存到本地
    :param url:文章中获取到的图片链接
    :param source:文件夹名称，根据平台名称进行创建文件
    :return:image_path 图片保存路径
    """
    # global Path
    # if source is None:
    #     Path = IMAGE_DIR + '\{}'.format(datetime.datetime.now().strftime("%Y-%m-%d"))
    # if source:
    #     Path = IMAGE_DIR + '\{}\{}'.format(source, datetime.datetime.now().strftime("%Y-%m-%d"))
    try:
        resp = requests.get(url, headers={"User-Agent": UserAgent().random})
        suffix = resp.headers['Content-Type'].split(";")[0].split('/')[1]
        if suffix in ['gif', 'png', 'jpg', 'jpeg']:
            pass
        else:
            suffix = resp.url.split('.')[-1]

        if not os.path.exists(IMAGE_DIR) and not os.path.isdir(IMAGE_DIR):
            os.makedirs(IMAGE_DIR)

        beforePath = '/'
        if sys.platform == "win32":
            image_path = IMAGE_DIR + '\{}.{}'.format(SetMd5(), suffix)
            pathList = image_path.split('\\')
        if sys.platform == "linux":
            image_path = IMAGE_DIR + '/{}.{}'.format(SetMd5(), suffix)
            pathList = image_path.split('/')
        with open(image_path, 'wb') as file:
            file.write(resp.content)
        afterPath = beforePath.join(pathList[pathList.index('img'):])
        return IMGURLHEAD + afterPath
    except requests.RequestException:
        return None


def SetMd5(params=None):
    md5 = hashlib.md5()
    if params:
        md5.update(str(params).encode('utf-8'))
    else:
        md5.update(str(time.time()).encode('utf-8'))
    md5Str = md5.hexdigest()
    return md5Str


if __name__ == '__main__':
    url = "https://xyimg1.qunliao.info/fastdfs6/M00/0A/32/rBUESWCHzlWAPXM9AAKDZOj6p34989.jpg"
    SaveImg(url)
